import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getAllGameType } from '@/api'
import { getGameDefaultKey, setGameDefaultKey } from '@utils'
import { GAME_STATUS_CODE, LotterCodeEnum } from '@/enum'
import { LotteryData } from '@/@types/game-store'

export const useGameStore = defineStore('game', () => {
  const gameList = ref([])

  const allGame = ref<LotteryData>({})
  const drawingStatus = ref(GAME_STATUS_CODE.weikaipan)

  const currentGame = ref(getGameDefaultKey())

  const latestGameData = ref<any>({})

  const currentSonGameTag = ref('')

  const currentHandicapCode = ref('')

  const getGameList = async () => {
    try {
      const { data } = await getAllGameType()
      const list = data.filter(({ lotteryCode }) => Object.values(LotterCodeEnum).includes(lotteryCode))
      allGame.value = list.reduce((map, item) => ((map[item.lotteryCode] = item), map), {})
      gameList.value = list
      currentHandicapCode.value = list[0]?.sysHandicapList[0]?.handicapCode
    } catch (e) {
      /* empty */
    }
  }

  const setCurrentGame = (lotteryCode: string) => {
    currentGame.value = lotteryCode
    setGameDefaultKey(lotteryCode)
  }

  // 当前开奖状态
  const setDrawingStatus = (status) => {
    const statusItem = Object.values(GAME_STATUS_CODE).find((item) => item.code === status)
    drawingStatus.value = statusItem !== undefined ? statusItem : GAME_STATUS_CODE.weikaipan
  }

  const resetDrawingStatus = () => {
    drawingStatus.value = { ...GAME_STATUS_CODE.weikaipan }
  }

  const setLatestGameData = (data) => {
    latestGameData.value = data
  }

  const setCurrentSonGame = (tag) => {
    currentSonGameTag.value = tag
  }
  
  const setHandicapCode = (code: string = '') => {
    if (code) return currentHandicapCode.value = code
    const handicapCode = gameList.value.find(item => item.lotteryCode===currentGame.value)?.sysHandicapList[0]?.handicapCode?? ''
    currentHandicapCode.value = handicapCode
  }

  return {
    gameList,
    getGameList,
    currentGame,
    setCurrentGame,
    allGame,
    drawingStatus,
    resetDrawingStatus,
    setDrawingStatus,
    setLatestGameData,
    latestGameData,
    setCurrentSonGame,
    currentSonGameTag,
    currentHandicapCode,
    setHandicapCode,
  }
}, {})
